package com.openxt.nbzj.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.openxt.nbzj.R;
import com.openxt.nbzj.adapter.RollViewAdapter;
import com.openxt.nbzj.adapter.ViewPagerAdapter;
import com.openxt.nbzj.model.ConfigModel;
import com.openxt.nbzj.model.RemotingModel;
import com.openxt.nbzj.remoting.RemotingEx;
import com.openxt.nbzj.util.SystemUtil;
import com.openxt.nbzj.view.RollView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.BindView;
import me.kaelaela.verticalviewpager.VerticalViewPager;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;

/**
 * Created by 颖杰_2 on 2016/7/7.
 */
public class HomeFragment extends OpenxtFragment implements RemotingEx.OnActionListener, ViewPager.OnPageChangeListener {

    @BindView(R.id.vertical_viewpager)
    VerticalViewPager verticalViewPager;

    @BindView(R.id.temperature)
    TextView temperature;
    @BindView(R.id.dayornight)
    ImageView dayornight;
    @BindView(R.id.pm25)
    TextView pm25;
    @BindView(R.id.describe)
    TextView describe;
    @BindView(R.id.describe_value)
    TextView describe_value;
    @BindView(R.id.news_roll_r)
    RelativeLayout news_roll_r;
    @BindView(R.id.news_roll)
    RollView news_roll;

    Handler mHandler = new Handler();

    RemotingModel remotingModel = null;
    Context mContext;
    List<OpenxtFragment> mList = new ArrayList<>();
    ViewPagerAdapter viewPagerAdapter = null;
    List<String> rollData = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_fragment, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();
        Utils.setLocalStorage(mContext, ConfigModel.HOME_LOADING, "true");
        remotingModel = new RemotingModel(mContext);

        ConfigModel.getSubscribes(mContext);
        initView();

        ContentNewsFragment newsFragment = new ContentNewsFragment();
        newsFragment.setHomeFragment(this);
        mList.add(newsFragment);
        ContentPartsFragment partsFragment = new ContentPartsFragment();
        partsFragment.setHomeFragment(this);
        mList.add(partsFragment);

        viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
        viewPagerAdapter.setList(mList);
        verticalViewPager.setAdapter(viewPagerAdapter);
        verticalViewPager.setCurrentItem(1);
        verticalViewPager.setOverScrollMode(View.OVER_SCROLL_NEVER);
        verticalViewPager.setOnPageChangeListener(this);
    }

    public void setCurrentItem(int position){
        verticalViewPager.setCurrentItem(position);
    }

    private void initView() {
        initWeatherGetweather();
        initWeatherGettrafficjam();
        initNewsGethot();

        if (ActivityUtil.isNetworkAvailable(mContext)) {
            remotingModel.getNewsGethot(this, false);
            remotingModel.getWeatherGetWeather(this, false);
            remotingModel.getWeatherGettrafficjam(this, false);
        }
    }

    private void initNewsGethot(){
        String val = Utils.getLocalStorage(getActivity(), ConfigModel.NEWS_GETHOT);
        if (StringUtil.isNull(val))
            return;
        try {
            final JSONArray data = JSON.parseArray(val);
            if(data.size() == 0)
                return;

            rollData = new ArrayList<>();
            for (int i = 0, j = data.size(); i < j && i < 3; i++) {
                JSONObject item = data.getJSONObject(i);
                String title = item.getString("TITLE");
                rollData.add(title);
            }
            if(news_roll.isStarted())
                news_roll.stop();
            news_roll.setAdapter(new RollViewAdapter(rollData));
            news_roll.start();
        } catch (Exception e) {

        }
    }
    private void initWeatherGetweather() {
        String val = Utils.getLocalStorage(getActivity(), ConfigModel.WEATHER_GETWEATHER);
        if (StringUtil.isNull(val))
            return;
        try {
            JSONObject data = JSON.parseObject(val);
            temperature.setText(data.getString("Temperature"));
            pm25.setText("PM2.5 | " + data.getString("Pm25"));

            /*String _dayornight = data.getString("DayOrNight");
            String _code = data.getString("Code");
            String img = "Content/images/weather/" + _dayornight + "/" + _code + ".png";
            dayornight.setImageBitmap(SystemUtil.getImageFromAssetsFile(img, getActivity()));*/
        } catch (Exception e) {

        }
    }

    private void initWeatherGettrafficjam() {
        String val = Utils.getLocalStorage(getActivity(), ConfigModel.WEATHER_GETTRAFFICJAM);
        if (StringUtil.isNull(val))
            return;
        try {
            JSONObject data = JSON.parseObject(val);
            describe.setText("拥堵指数 | " + data.getString("Value"));
            describe_value.setText(data.getString("Describe"));
        } catch (Exception e) {

        }
    }

    @Override
    public void refresh() {
        String home_loading = Utils.getLocalStorage(mContext, ConfigModel.HOME_LOADING);
        if("true".equals(home_loading))
            return;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(mList == null || mList.isEmpty())
                    return;
                mList.get(1).refresh();
            }
        }, 10);
        Utils.setLocalStorage(mContext, ConfigModel.HOME_LOADING, "true");
    }

    @Override
    public void willBeDisplayed() {

    }

    @Override
    public void onActionCompleted(String reVal, String actionName) {
        Utils.setLocalStorage(mContext, actionName, reVal);
        if (ConfigModel.WEATHER_GETWEATHER.equals(actionName)) {
            initWeatherGetweather();
        } else if (ConfigModel.WEATHER_GETTRAFFICJAM.equals(actionName)) {
            initWeatherGettrafficjam();
        } else if (ConfigModel.NEWS_GETHOT.equals(actionName)) {
            initNewsGethot();
        }
    }

    @Override
    public void onActionFailed(String errorVal, String actionName) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if(position == 0){
            news_roll_r.setVisibility(View.GONE);
        }else if(position == 1){
            news_roll_r.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
